<template>
  <view>
    <view class="uni-header">
      <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
      <view class="uni-group">
        <button @click="exportApi" class="uni-button" type="primary" size="mini">导出接口</button>
        <button @click="syncApi" class="uni-button" type="primary" size="mini">同步接口</button>
        <button @click="clickForm($t('common.button.add') + '接口')" class="uni-button" type="primary"
          size="mini">{{$t('common.button.add')}}接口</button>
        <button class="uni-button" type="warn" size="mini"
          @click="clickDelete(getSelectIds())">{{$t('common.button.batchDelete')}}</button>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="condition.keywords" @confirm="search"
          :placeholder="$t('common.placeholder.query')" />
        <button class="uni-button" type="primary" size="mini" @click="search">{{$t('common.button.search')}}</button>
        <button class="uni-button" type="default" size="mini"
          @click="reset">{{$t('common.button.reset')}}{{$t('common.button.search')}}</button>
      </view>
    </view>
    
    <view class="uni-container">  
      <uni-table ref="table" :loading="loading" emptyText="没有更多数据" border stripe type="selection"
        @selection-change="selectionChange">
        <uni-tr>
          <uni-th align="center" width="120" filter-type="select" :filter-data="filterPlatformList" @filter-change="filterChange($event, 'platform')">平台</uni-th>
          <uni-th align="center" width="120" filter-type="search" @filter-change="filterChange($event, 'path')">地址</uni-th>
          <uni-th align="center" width="120">描述</uni-th>
          <uni-th align="center" width="150" filter-type="select" :filter-data="filterAuthList" @filter-change="filterChange($event, 'authIds')">关联权限</uni-th>
          <uni-th align="center" width="150" filter-type="select" :filter-data="filterCreatedTypeList" @filter-change="filterChange($event, 'createdType')">添加方式</uni-th>
          <uni-th align="center" width="150" filter-type="select" :filter-data="filterAnonymousList" @filter-change="filterChange($event, 'anonymous')">匿名访问</uni-th>
          <uni-th align="center" width="150" filter-type="select" :filter-data="filterAllowList" @filter-change="filterChange($event, 'allow')">允许访问</uni-th>
          <uni-th align="center" width="150">状态</uni-th>
          <uni-th align="center" width="300">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item,index) in items" :key="index">
          <uni-td align="center">{{item.platformName}}</uni-td>
          <uni-td align="center">{{item.path}}</uni-td>
          <uni-td align="center">{{item.description}}</uni-td>
          <uni-td align="center">{{item.authNames}}</uni-td>
          <uni-td align="center">{{item.createdTypeName}}</uni-td>
          <uni-td align="center">
            <switch style="zoom: 0.8;" :checked="item.anonymous == 1"
              @change="tableUpdateField({value:$event.detail.value, id:item.id, field:'anonymous' })" />
          </uni-td>
          <uni-td align="center">
            <switch style="zoom: 0.8;" :checked="item.allow == 1"
              @change="tableUpdateField({value:$event.detail.value, id:item.id, field:'allow' })" />
          </uni-td>
          <uni-td align="center">{{item.statusName}}</uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button @click="clickForm(item.path, item.id)" class="uni-button" size="mini"
                type="primary">{{$t('common.button.edit')}}</button>
              <button @click="clickDelete([item.id])" class="uni-button" size="mini"
                type="warn">{{$t('common.button.delete')}}</button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <uni-pagination show-icon show-page-size :page-size="pageSize" v-model="pageCurrent" :current="pageCurrent" :total="total"
        @change="changePage" @pageSizeChange="changeSize" />
    </view>
  </view>
  <fix-window />

</template>


<script>
  import {
    mapActions
  } from "vuex"
  export default {
    data() {
      return {
        pageSize: 20,
        pageCurrent: 1,
        total: 0,
        items: [],
        loading: true,
        selectIds: [],
        condition: {
          keywords: "",
        },
        conditionData: {
        },
      }
    },
    computed: {
      filterAnonymousList() {
		  return this._conditionalParameterAdapter(this.conditionData.anonymous);
      },
      filterAllowList() {
		  return this._conditionalParameterAdapter(this.conditionData.allow);
      },
      filterCreatedTypeList() {
		  return this._conditionalParameterAdapter(this.conditionData.createdType);
      },
      filterAuthList() {
        return this._conditionalParameterAdapter(this.conditionData.authIds);
      },
      filterPlatformList() {
		  return this._conditionalParameterAdapter(this.conditionData.platform);
      }
    },
    onLoad() {
      this.form().then(data => {
		  console.log(data);
        this.conditionData = data;
      });
    },
    onShow() {
      this.search()
    },
    methods: {
      ...mapActions('api', ['sync', 'list', 'save', 'delete', 'form', 'updateField', 'exportJSON']),
      clickForm(title, id = 0) {
        uni.navigateTo({
          url: `/pages/unify/api/form?title=${title}&id=${id}`
        })
      },
      exportApi() {
        this.exportJSON().then(data => {
          console.log(data);
          // 创建 Blob 对象
          const blob = new Blob([JSON.stringify(data.openApi, null, 2)], {
            type: 'application/json'
          });

          // 创建下载链接并触发点击
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = 'openapi.json';
          link.click();

          // 释放 Blob 对象的 URL
          URL.revokeObjectURL(url);
        })
      },
      syncApi() {
        uni.showLoading({
          mask: true,
          title: "同步中"
        })
        this.sync().then(_ => {
          uni.showToast({
            title: "同步成功",
            icon: "success",
            mask: true
          })
          this.search()
        }).finally(_ => {
          uni.hideLoading()
        })
      },
      clickDelete(ids) {
        const that = this
        uni.showModal({
          title: "确认删除指定记录吗？",
          success(e2) {
            if (e2.cancel) {
              return;
            }
            that.delete({
              ids
            }).then(_ => {
              uni.showToast({
                title: "操作成功"
              })
              that.search();
            })
          }
        })
      },
      // 搜索
      search() {

        this.selectIds = [];
        if (this.$refs.table) {
          this.$refs.table.clearSelection();
        }
        
        
        this.loading = true
        this.items = [];
        let conditionCopy = JSON.parse(JSON.stringify(this.condition))
        conditionCopy.page = this.pageCurrent;
        conditionCopy.limit = this.pageSize;
        this.list(conditionCopy).then(data => {
          this.items = data.list
          this.total = data.count
          this.loading = false
        });
      },
      reset() {
        this.condition.keywords = "";
        this.search();
      },
      tableUpdateField(e) {
        this.updateField({
          ids: [e.id],
          field: e.field,
          value: e.value
        }).finally(_ => {
          this.search();
        })
      },
      changeSize(e) {
        this.pageSize = e;
        this.pageCurrent = 1;
        this.search()
      },
      changePage(e) {
        this.pageCurrent = e.current;
        this.search()
      },
      getSelectIds() {
        if (!this.selectIds.length) {
          uni.showToast({
            title: "请指定操作的记录",
            icon: "none"
          })
          throw new Error("请指定操作的记录");
        }
        return this.selectIds
      },
      selectionChange(e) {
        this.selectIds = []
        e.detail.index.forEach(index => {
          this.selectIds.push(this.items[index].id)
        })
      },
      filterChange(e, field) {
        switch (e.filterType) {
          case "search":
            this.condition[field] = e.filter
            break
          case "select":
            this.condition[field] = e.filter
            break
          case "range":
            this.condition[field] = e.filter
            break;
          case "date":
          case "timestamp":
            if (e.filter[0]) {
              e.filter[0] /= 1000
            }
            if (e.filter[1]) {
              e.filter[1] /= 1000
            }
            this.condition[field] = e.filter
            break;
        }
      
        this.search()
      },
    }
  }
</script>